package com.jumi.microservice.rocketmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.jumi.microservice.dto.logistics.AutoSpiltRequest;
import com.jumi.microservice.service.logistics.AutoSpiltService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author mazhao
 * @Date 2020-09-17 11:50
 */
@Component
public class AutoSpiltOrderListener implements MessageListener {

    private static final Logger log = LoggerFactory.getLogger(AutoSpiltOrderListener.class);

    @Resource
    AutoSpiltService autoSpiltService;
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    private static final String key = "isAutoSpiltOrder::";

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        log.info("自动拆单收到消息：[{}]", new String(message.getBody()));
        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(new String(message.getBody()));
        } catch (Exception e) {
            log.error("JSON解析消息出错 [{}]",e.getMessage());
            return Action.CommitMessage;
        }
        String orderNo = jsonObject.getString("orderNo");
        try {
            AutoSpiltRequest request = new AutoSpiltRequest();
            request.setOrderNo(orderNo);
            Boolean res = redisTemplate.opsForValue().setIfAbsent(key+orderNo,"自动拆单",7,TimeUnit.DAYS);
            if(res!=null && !res){
                log.info("重复订单：[{}]", orderNo);
                return Action.CommitMessage;
            }
            autoSpiltService.autoSpiltOrder(request);
            return Action.CommitMessage;
        } catch (Exception e) {
            redisTemplate.delete(key+orderNo);
            //消费失败，挂起当前队列
            log.error("自动拆单出错 [{}]",e.getMessage());
            return Action.ReconsumeLater;
        }
    }
}
